//
//  AppDelegate.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/13.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // 设置全局的navigationBar的外观
        UINavigationBar.appearance().tintColor = UIColor.orange
        UITabBar.appearance().tintColor = UIColor.orange
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(changeRootViewController(notify:)), name: NSNotification.Name(ZHTQViewControllerChangeNotification), object: nil)
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = loadingViewController()
        window?.makeKeyAndVisible()
        
        
        return true
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension AppDelegate{
    
    ///监听转换rootwindow控制器通知
    @objc private func changeRootViewController(notify: Notification) {
        if notify.object as! Bool{
            
            window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
            
        } else {
            
            window?.rootViewController = UIStoryboard(name: "Welcome", bundle: nil).instantiateInitialViewController()!
        }
    }
    
    /// 返回应该显示的控制器
    private func loadingViewController() -> UIViewController{
        if UserAccount.isLogin() { // 登录
            
            if isNewVersion() { //新版本
                return UIStoryboard(name: "Newfeature", bundle: nil).instantiateInitialViewController()!
            } else { // 没有新版本
                return UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
            }
            
        } else { //未登录
            
            return UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
        }
    }
    
    /// 判断当前是否有新版本
    private func isNewVersion() -> Bool{
        // 获取当前版本号
        let currentVr = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String
        let version = UserDefaults.standard.object(forKey: "vr") as? String ?? "0.0"
        if currentVr?.compare(version) == ComparisonResult.orderedDescending {
            ZHLog("new")
            
            // 保存最新的版本号
            UserDefaults.standard.set(currentVr, forKey: "vr")
            UserDefaults.standard.synchronize()
            return  true
        }
        
        ZHLog("none")
        return false
    }
}

//MARK:- 自定义log
///自定义log 只在debug模式下打印
func ZHLog<T>(_ message: T, fileName: String = #file, methodName: String = #function, line: Int = #line){
    #if DEBUG
    print("\(fileName.components(separatedBy: "/").last!).\(methodName)[\(line)]:\(message)")
    #endif
}
